import { traverseArray } from "@/utils";

function createAPI(baseURL: string) {
  function request(conf: any) {
    return new Promise((resolve, reject) => {
      const data = traverseArray(conf.opts?.data || {}, true);
      uni.$tm.fetch
        .request({
          url: baseURL + conf.url,
          method: conf.method || "POST",
          data,
          header: {
            ...{
              ticket: uni.getStorageSync("ticket") || "",
              "Content-Type": "application/x-www-form-urlencoded",
            },
            ...conf.opts?.header,
          },
        })
        .then((params: any) => {
          //获取当前页面地址
          const currentPage = getCurrentPages()[getCurrentPages().length - 1];
          if (
            params.data &&
            params.data.status === 401 &&
            conf.url.indexOf("/sso/login") === -1 &&
            //首页不跳转到登陆页,做提示然后停留在原地,清除本地ticket
            !currentPage?.route?.includes("pages/index/index")
          ) {
            reject(params.data);
           /* //防止重复跳转和多次提示
            if (uni.getStorageSync("isToLoginPage")) {
              return;
            }
            uni.setStorageSync("isToLoginPage", true);
            uni.removeStorageSync("ticket");
            uni.showModal({
              title: "提示",
              content: "登陆失效",
              showCancel: false,
              success() {
                uni
                  .reLaunch({
                    url: "/pages/login/index",
                  })
                  .finally(() => {
                    uni.removeStorageSync("isToLoginPage");
                  });
              },
            });*/
          } else if (params.data && params.data.status === 200) {
            resolve(params.data);
          } else {
            reject(params.data);
            if (params.data.status === 401) {
              uni.removeStorageSync("ticket");
            }
            /*uni
              .showModal({
                title: "提示",
                content: params.data.message || "服务异常",
                showCancel: false,
              })
              .then();*/
          }
        })
        .catch((e) => {
          setTimeout(() => {
            /*uni
              .showModal({
                title: "提示",
                content: "网络异常",
                showCancel: false,
              })
              .then();*/
          });
          console.error(e);
          // 网络异常
          reject(e);
        });
    });
  }

  return function (conf: any) {
    conf = conf || {};
    const i = request(conf);
    return i as Promise<unknown> as Promise<{
      data: any;
      status: number;
      message: string;
      total?: number;
    }>;
  };
}

function convertRESTAPI(url: string, opts: any) {
  if (!opts || !opts.path) return url;

  const pathKeys = Object.keys(opts.path);

  pathKeys.forEach((key) => {
    const r = new RegExp("(:" + key + "|{" + key + "})", "g");
    url = url.replace(r, opts.path[key]);
  });

  return url;
}

//用于获取文件可以查看的地址用于图片展示和视频预览等
function getDownloadPath(filePath: string, basePath = "/tms-web") {
  return `${import.meta.env.VITE_SERVICE_URL}${basePath}/file/download?ticket=${uni.getStorageSync("ticket")}&path=${filePath}`;
}

export { createAPI, convertRESTAPI, getDownloadPath };
